package com.lyh.service.impl;

import com.lyh.mapper.UserMapper;
import com.lyh.pojo.Person;
import com.lyh.pojo.PersonAndUser;
import com.lyh.pojo.Result;
import com.lyh.pojo.User;
import com.lyh.utils.*;
import com.lyh.service.UserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
@CacheConfig(cacheNames = {"user"}) //可以给类中方法的缓存都加上统一的user::前缀
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JedisPoolUtils jedis;

    @Autowired
    private EmailUtils emailUtils;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    //@Autowired //发送邮件的对象
    //private JavaMailSenderImpl mailSender;

    @Override
    @Transactional(timeout = 5)//开启事务
    public int register(PersonAndUser user) {
        User newUser = new User();
        //散列与加密
        String salt = SaltUtils.getSalt(8);

        //对密码进行加密
        Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 1024);//最后一个是散列次数

        newUser.setUsername(user.getUsername());
        newUser.setPhone(user.getPhone());
        newUser.setSalt(salt);
        newUser.setPassword(md5Hash.toHex());//保存加密后的密码
        //默认激活状态都是false
        newUser.setActive(false);

        Person person = new Person();
        Date birthday = null;
        try {
            birthday = sdf.parse(user.getBirthday());
        } catch (ParseException e) {
            e.printStackTrace();
        }

        person.setEmail(user.getEmail());
        person.setBirthday(birthday);
        person.setGender(user.getGender());
        person.setIdentify(user.getIdentify());
        person.setRealname(user.getRealname());

        try{
            userMapper.registerUser(newUser);//返回的int只是影响条数, auto的数值会自动填充到该对象中
            Integer id = newUser.getUserId();
            //将返回的auto_increment id设置
            person.setUserId(id);
            userMapper.registerPerson(person);
        } catch (Exception e){
            e.printStackTrace();
            return 0;//数据保存发生异常
        }
        System.out.println("注册用户, 保存操作完成!!!");
        //异步发送邮件
        emailUtils.sendMail(user);
        System.out.println("发送邮件异步任务已启动!!!");
        return 1;
    }

    //@Async
    //public void sendMail(PersonAndUser user){
    //    //数据保存成功, 生成邮箱激活码
    //    MimeMessage mimeMessage = mailSender.createMimeMessage();
    //    try {
    //        String username = user.getUsername();
    //        String active = UUIDUtils.getUUID();
    //        //创建激活码并存放到redis中
    //        jedis.setLimitTimeValue(username, active,60*60*48);//有48小时的有效时间
    //
    //        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
    //        helper.setSubject("12354山卡拉火车网--激活邮件");
    //        helper.setText(HtmlCode.getHtml(username,active),true);//true可以解析html代码
    //        helper.setTo(user.getEmail());//获取用户的注册邮箱
    //        helper.setFrom("2597247763@qq.com");
    //        mailSender.send(mimeMessage);//发送邮件
    //    } catch (MessagingException e) {
    //        logger.error("创建复杂邮件对象发生错误!");
    //        e.printStackTrace();
    //    }
    //}

    //带有参数的方法缓存
    @Cacheable(value = "user", key = "#root.methodName+#username")
    public User queryUserByUsername(String username) {
        return userMapper.queryUserByUsername( username );
    }

    @Override
    public User queryUserByPhone(String phone) {
        return userMapper.queryUserByPhone(phone);
    }

    @Override
    public PersonAndUser getUserDetail(String id) {
        PersonAndUser personAndUser = userMapper.queryUserDetailByUsername(id);
        //加密敏感信息
        TackleDataUtils.phoneAndIdentify(personAndUser);

        return personAndUser;
    }

    @Override
    public Result<String> checkDuplicate(PersonAndUser personAndUser) {
        Result<String> result = new Result<>();
        String username = personAndUser.getUsername();
        if(userMapper.queryUserByUsername(username)!=null){
            logger.info("用户名已存在!");
            return ResultUtils.getResult(false,"用户名已存在!",1);
        }

        String phone = personAndUser.getPhone();//手机号
        if(userMapper.queryUserByPhone(phone)!=null){
            logger.info("电话号码已存在!");
            return ResultUtils.getResult(false,"电话号码已存在!",2);
        }

        String email = personAndUser.getEmail();//邮箱
        if(userMapper.queryUserByEmail(email)!=null){
            logger.info("邮箱已存在!");
            return ResultUtils.getResult(false,"邮箱已存在!",3);
        }

        String identify = personAndUser.getIdentify();//身份证
        if(userMapper.queryUserByIdentify(identify) != null){
            logger.info("身份证已存在!");
            return ResultUtils.getResult(false,"身份证已存在!",4);
        }
        return ResultUtils.getResult(true,"用户已完成注册!",5);
    }


    @Override
    public int active(String username, String active) {
        //激活流程
        // 1.先查询数据库中该账号是否被激活 , 如果是就直接返回状态 2

        try {
            if(userMapper.queryActive(username)==1){
                return 2;//查询结果为已激活, 返回状态2
            }
        } catch (Exception e) {
            logger.error("激活查询异常, 没有查询到用户名为:"+username+"的用户!");
            return 0;
        }
        // 2.去redis中查询, 查询是否含有激活码
        String value = jedis.getValue(username);
        if(value!=null&&value.equals(active)){
            //激活码匹配, 激活用户
            userMapper.activeUser(username);
            //将激活码删除
            jedis.removeValue(username);
            return 1;
        }

        // 3.如果查询到但是不正确返回0
        return 0;
    }

}
